#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>

char* calculate_file_sha1(const char* filepath) {
    FILE* file = fopen(filepath, "rb");
    if (!file) {
        perror("Failed to open file");
        return NULL;
    }

    unsigned char buffer[4096];
    unsigned char digest[SHA_DIGEST_LENGTH];
    SHA_CTX sha_ctx;

    SHA1_Init(&sha_ctx);

    size_t bytes_read;
    while ((bytes_read = fread(buffer, 1, sizeof(buffer), file)) != 0) {
        SHA1_Update(&sha_ctx, buffer, bytes_read);
    }

    SHA1_Final(digest, &sha_ctx);

    fclose(file);

    char* sha1_string = (char*)malloc(SHA_DIGEST_LENGTH * 2 + 1);
    if (!sha1_string) {
        perror("Failed to allocate memory for SHA1 string");
        return NULL;
    }

    for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) {
        sprintf(&sha1_string[i * 2], "%02x", digest[i]);
    }

    return sha1_string;
}

// 示例用法
int main() {
    const char* filepath = "/home/bsh/xiyouji.txt";
    char* sha1 = calculate_file_sha1(filepath);
    if (sha1) {
        printf("SHA1: %s\n", sha1);
        free(sha1);
    }
    return 0;
}